using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;

namespace LayoutPlanning.Converters
{
    public class ValueToThicknessConverter : IMultiValueConverter, IValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values == null || values.Length < 2 || values.Any(t => t == DependencyProperty.UnsetValue))
                return new Thickness(0);

            var p = (double) (int) values[0];
            if (values[1] is FrameworkElement)
            {
                var par = (FrameworkElement) values[1];
                var max = Math.Min(par.ActualHeight, par.ActualWidth);
                p = (3 - p)*max/9;
                var top = p;
                var hori = p;
                if (par.ActualWidth > par.ActualHeight)
                    hori += (par.ActualWidth - par.ActualHeight)/2;
                else
                    top += (par.ActualHeight - par.ActualWidth)/2;
                return new Thickness(hori, top, hori, top);
            }
            return new Thickness(p);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return new Thickness(0);

            var p = (double) (int) value;
            if (parameter is FrameworkElement)
            {
                var par = (FrameworkElement) parameter;
                var max = Math.Max(par.ActualHeight, par.ActualWidth);
                p = (3 - p)*max/3;
            }
            return new Thickness(p);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}